﻿using System.Linq;
using System.Threading.Tasks;
using Service.Model.Context;
using Service.Workflow.PlayerHeuristic.Command;
using ShortBus;

namespace Service.Workflow.Player.Command
{
    public class CreatePlayerCommandHandler : IAsyncQueryHandler<CreatePlayerCommand, CreatePlayerCommandResponse>
    {
        private readonly ServiceDbContext dbContext;
        private readonly IMediator mediator;

        public CreatePlayerCommandHandler(ServiceDbContext serviceDbContext, IMediator mediator)
        {
            this.dbContext = serviceDbContext;
            this.mediator = mediator;
        }

        public async Task<CreatePlayerCommandResponse> HandleAsync(CreatePlayerCommand command)
        {
            
            var player = new Model.Player()
            {
                Difficulty = command.Difficulty,
                PlayerColor = command.Color
            };

            dbContext.Players.Add(player);

            await dbContext.SaveChangesAsync();

            if (command.Heuristics == null || !command.Heuristics.Any())
            {
                return new CreatePlayerCommandResponse() { PlayerId = player.PlayerId };
            }

            var heuristics = dbContext.Heuristics.Where(h => command.Heuristics.Contains(h.HeuristicId)).ToList();
            if (heuristics.Any())
            {
                var createPlayerHeuristicsCommandResponse = await mediator.RequestAsync(new CreatePlayerHeuristicsCommand()
                {
                    HeuristicIds = heuristics.Select(h => h.HeuristicId).ToList(),
                    PlayerId = player.PlayerId
                });
            }

             

            return new CreatePlayerCommandResponse() { PlayerId = player.PlayerId };
        }
    }
}